package cn.yikaojiuguo.student.ui.my;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.yikaojiuguo.student.R;
import cn.yikaojiuguo.student.app.YiKaoApplication;
import cn.yikaojiuguo.student.bean.MessageEvent;
import cn.yikaojiuguo.student.support.simple.ArgsConstants;
import cn.yikaojiuguo.student.support.simple.UrlConstants;
import cn.yikaojiuguo.student.support.utils.ImageManager;
import cn.yikaojiuguo.student.support.utils.LogUtil;
import cn.yikaojiuguo.student.support.utils.QiniuUploadUtils;
import cn.yikaojiuguo.student.support.utils.RequestUtil;
import cn.yikaojiuguo.student.support.utils.ToastUtil;
import cn.yikaojiuguo.student.support.utils.Util;
import cn.yikaojiuguo.student.support.volley.Response;
import cn.yikaojiuguo.student.ui.base.CustomerActionBarActivity;
import cn.yikaojiuguo.student.ui.view.FixedDatePickerDialog;
import cn.yikaojiuguo.student.ui.view.RoundImageView;

public class MyInfoActivity extends CustomerActionBarActivity implements View.OnClickListener,
        ImageManager.OnFinishCompressListener, UpCompletionHandler {

    private ImageManager mImageManager;

    @Bind(R.id.rl_avatar)
    RelativeLayout mRl_avatar;
    @Bind(R.id.ri_avatar)
    RoundImageView mAvatar;
    @Bind(R.id.rl_nick)
    RelativeLayout mRl_nick;
    @Bind(R.id.tv_nick)
    TextView mTv_nick;
    @Bind(R.id.rl_sex)
    RelativeLayout mRl_sex;
    @Bind(R.id.tv_sex)
    TextView mTv_sex;
    @Bind(R.id.rl_birth)
    RelativeLayout mRl_birth;
    @Bind(R.id.tv_birth)
    TextView mTv_birth;
    @Bind(R.id.tv_major)
    TextView mTv_major;
    @Bind(R.id.rl_major)
    RelativeLayout mRl_major;
    @Bind(R.id.rl_root)
    RelativeLayout mRl_root;
    @Bind(R.id.rl_grade)
    RelativeLayout mRl_grade;
    @Bind(R.id.rl_provice)
    RelativeLayout mRl_province;
    @Bind(R.id.tv_grade)
    TextView mTv_grade;
    @Bind(R.id.tv_province)
    TextView mTv_province;

    //修改昵称弹出框相关的View
    private View mDialogViewInputName;
    private EditText mEt_name;
    private Button mBtn_nick_ok;
    private Button mBtn_nick_cancel;
    private String mNickName;

    //修改性别弹出框相关的View
    private View mDialogViewSex;
    private RelativeLayout mRl_man;
    private RelativeLayout mRl_woman;
    private ImageView mIv_man;
    private ImageView mIv_woman;
    private int mSex;

    private DatePickerDialog datePickerDialog;
    //唯一的弹出框对象，不同的弹出框加载不同的View
    private AlertDialog mDialog;

    private InfoChoosePopupWindow mPopupWindow;

    public static Intent newIntent() {
        Intent intent = new Intent(YiKaoApplication.getInstance(), MyInfoActivity.class);
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_info);
        ButterKnife.bind(this);
        initView();
        initEvents();
    }

    private void initView() {
        ImageLoader.getInstance().displayImage(YiKaoApplication.getUserAvatar(), mAvatar);
        mTv_nick.setText(YiKaoApplication.getUserName());
        mTv_major.setText(YiKaoApplication.getMajorName());
        mTv_grade.setText(YiKaoApplication.getGradeName());
        mTv_province.setText(YiKaoApplication.getProvinceName());
        mTv_birth.setText(YiKaoApplication.getUserBirth());
        resetSexText();

        mDialogViewInputName = View.inflate(this, R.layout.layout_dialog_input_name, null);
        mEt_name = (EditText) mDialogViewInputName.findViewById(R.id.et_name);
        mBtn_nick_cancel = (Button) mDialogViewInputName.findViewById(R.id.btn_nick_cancel);
        mBtn_nick_ok = (Button) mDialogViewInputName.findViewById(R.id.btn_nick_ok);

        mDialogViewSex = View.inflate(this, R.layout.layout_dialog_change_sex, null);
        mRl_man = (RelativeLayout) mDialogViewSex.findViewById(R.id.rl_man);
        mRl_woman = (RelativeLayout) mDialogViewSex.findViewById(R.id.rl_woman);
        mIv_man = (ImageView) mDialogViewSex.findViewById(R.id.iv_man);
        mIv_woman = (ImageView) mDialogViewSex.findViewById(R.id.iv_woman);
        mSex = YiKaoApplication.getUserSex();
        resetSexChooseState();

        AlertDialog.Builder builder = new AlertDialog.Builder(this, AlertDialog
                .THEME_DEVICE_DEFAULT_LIGHT);
        mDialog = builder.create();

    }

    private void resetSexChooseState() {
        switch (mSex) {
            case 0:
                mIv_man.setVisibility(View.INVISIBLE);
                mIv_woman.setVisibility(View.INVISIBLE);
                break;
            case 1:
                mIv_man.setVisibility(View.VISIBLE);
                mIv_woman.setVisibility(View.INVISIBLE);
                break;
            case 2:
                mIv_man.setVisibility(View.INVISIBLE);
                mIv_woman.setVisibility(View.VISIBLE);
                break;
        }
    }

    private void resetSexText() {
        int sex = YiKaoApplication.getUserSex();
        switch (sex) {
            case 0:
                mTv_sex.setText("");
                break;
            case 1:
                mTv_sex.setText("男");
                break;
            case 2:
                mTv_sex.setText("女");
                break;
        }
    }

    private void initEvents() {
        mImageManager = new ImageManager(this);
        mImageManager.setOnFinishCompressListener(this);
        mRl_avatar.setOnClickListener(this);
        mRl_nick.setOnClickListener(this);
        mBtn_nick_ok.setOnClickListener(this);
        mBtn_nick_cancel.setOnClickListener(this);
        mRl_sex.setOnClickListener(this);
        mRl_man.setOnClickListener(this);
        mRl_woman.setOnClickListener(this);
        mRl_birth.setOnClickListener(this);
        mRl_major.setOnClickListener(this);
        mRl_grade.setOnClickListener(this);
        mRl_province.setOnClickListener(this);
        Calendar c = Calendar.getInstance();
        DatePickerDialog.OnDateSetListener listener = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                String birth = year + "-" + (monthOfYear+1) + "-" + dayOfMonth;
                LogUtil.showInfoLog("date","birth = " + birth);
                changeBirth(birth);
            }
        };
        datePickerDialog = new FixedDatePickerDialog(this, AlertDialog
                .THEME_HOLO_LIGHT, listener, c.get(Calendar.YEAR), c
                .get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
    }

    private void changeBirth(final String birth) {
        showProgressDialog("正在修改生日...");
        String requestUrl = null;
        try {
            requestUrl = UrlConstants.CHANGE_BIRTH + "&mid=" + YiKaoApplication.getUserId() +
                    "&birthday=" + URLEncoder.encode(birth, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        RequestUtil.requestGet(requestUrl, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                dismissProgressDialog();
                if(response!=null && response.optBoolean("success")) {
                    YiKaoApplication.putUserBirth(birth);
                    mTv_birth.setText(YiKaoApplication.getUserBirth());
                }
            }
        }, null, mTag);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_avatar:
                mImageManager.setNeedCrop(true).setRatio(1, 1);
                mImageManager.showDialog();
                break;
            case R.id.rl_nick:
                showNickNameInputDialog();
                break;
            case R.id.btn_nick_cancel:
                if (mDialog != null && mDialog.isShowing()) {
                    mDialog.dismiss();
                }
                break;
            case R.id.btn_nick_ok:
                if (checkNickName()) {
                    mDialog.dismiss();
                    showProgressDialog("正在修改昵称...");
                    String requestUrl = null;
                    try {
                        requestUrl = UrlConstants.CHANGE_NICK_NAME + "&mid=" +
                                YiKaoApplication.getUserId() + "&username=" + URLEncoder.encode
                                (mNickName, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    RequestUtil.requestGet(requestUrl, new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            dismissProgressDialog();
                            if (response != null && response.optBoolean("success")) {
                                YiKaoApplication.putUserName(mNickName);
                                YiKaoApplication.changeUserInfoCache(true);
                                mTv_nick.setText(YiKaoApplication.getUserName());
                                ToastUtil.showToast(MyInfoActivity.this, "昵称修改成功");
                            }
                        }
                    }, null, mTag);
                } else {
                    ToastUtil.showToast(this, "用户名长度为1到10，只可以包含汉字，字母，数字，下划线");
                }
                break;
            case R.id.rl_sex:
                showChangeSexDialog();
                break;
            case R.id.rl_man:
                mSex = 1;
                changeSex();
                break;
            case R.id.rl_woman:
                mSex = 2;
                changeSex();
                break;
            case R.id.rl_birth:
                showDatePickerDialog();
                break;
            case R.id.rl_major:
                showChooseMajorDialog();
                break;
            case R.id.rl_grade:
                showChooseGradeDialog();
                break;
            case R.id.rl_provice:
                showChooseProviceDialog();
                break;
        }
    }

    private void showChooseProviceDialog() {
        mPopupWindow = new InfoChoosePopupWindow(this,0.8f,0.5f,InfoChoosePopupWindow.CHOOSE_PROVINCE);
        mPopupWindow.setAnimationStyle(android.R.style.Animation_Dialog);
        mPopupWindow.showAtLocation(mRl_root, Gravity.CENTER,0,0);
    }

    private void showChooseGradeDialog() {
        mPopupWindow = new InfoChoosePopupWindow(this,0.8f,0.5f,InfoChoosePopupWindow.CHOOSE_GRADE);
        mPopupWindow.setAnimationStyle(android.R.style.Animation_Dialog);
        mPopupWindow.showAtLocation(mRl_root, Gravity.CENTER,0,0);

    }

    private void showChooseMajorDialog() {
        mPopupWindow = new InfoChoosePopupWindow(this,0.8f,0.5f,InfoChoosePopupWindow.CHOOSE_MAJOR);
        mPopupWindow.setAnimationStyle(android.R.style.Animation_Dialog);
        mPopupWindow.showAtLocation(mRl_root, Gravity.CENTER,0,0);
    }

    private void showDatePickerDialog() {
        datePickerDialog.show();
    }

    private void changeSex() {
        resetSexChooseState();
        mDialog.dismiss();
        showProgressDialog("正在修改性别...");
        String requestUrl = UrlConstants.CHANGE_SEX + "&mid=" + YiKaoApplication.getUserId() +
                "&sex=" + mSex;
        RequestUtil.requestGet(requestUrl, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                dismissProgressDialog();
                if (response != null && response.optBoolean("success")) {
                    YiKaoApplication.putUserSex(mSex + "");
                    resetSexText();
                    ToastUtil.showToast(MyInfoActivity.this, "性别修改成功");
                }
            }
        }, null, mTag);
    }

    private void showChangeSexDialog() {
        showDialog(mDialogViewSex);
    }

    private void showDialog(View contentView) {
        mDialog.show();
        Window window = mDialog.getWindow();
        window.setBackgroundDrawableResource(android.R.color.transparent);
        ViewParent parent = contentView.getParent();
        if (parent != null && parent instanceof ViewGroup) {
            ((ViewGroup) parent).removeAllViews();
        }
        window.setContentView(contentView);
        window.setLayout((int) (Util.getScreenWidthPixels(this) * 0.8), ViewGroup
                .LayoutParams.WRAP_CONTENT);
    }

    private boolean checkNickName() {
        mNickName = mEt_name.getText().toString().trim();
        //只含有汉字、数字、字母、下划线，下划线位置不限，长度1到10
        Pattern p = Pattern.compile("^[a-zA-Z0-9_\u4e00-\u9fa5]{1,10}$");
        Matcher m = p.matcher(mNickName);
        return m.matches();
    }

    private void showNickNameInputDialog() {
        showDialog(mDialogViewInputName);
        Window window = mDialog.getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager
                .LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        Util.openSoftInput(mDialogViewInputName);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        mImageManager.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onCompressFinish() {
        //压缩完成，开始上传
        setProgressMsg("正在上传...");
        String requestUrl = UrlConstants.UPLOAD_AVATAR + "&mid=" + YiKaoApplication.getUserId();
        QiniuUploadUtils.uploadSingleImg(this, requestUrl, YiKaoApplication.getCacheImgPath() +
                "/" + ArgsConstants.UPLOAD_IMAGE, this, null);
    }

    @Override
    public void complete(String key, ResponseInfo info, JSONObject response) {
        dismissProgressDialog();
        if (info != null && info.statusCode == 200) {
            ToastUtil.showToast(this, "头像修改成功");
            String avatar = UrlConstants.QINIU_IMG_HEADER + YiKaoApplication.getUploadImgName();
            YiKaoApplication.putUserAvatar(avatar);
            ImageLoader.getInstance().displayImage(YiKaoApplication.getUserAvatar(), mAvatar);
            YiKaoApplication.changeUserInfoCache(true);
        } else {
            LogUtil.showInfoLog("upload error", info.error);
        }

    }

    @Override
    public void onEvent(MessageEvent event) {
        super.onEvent(event);
        if(event.messageType == MessageEvent.MessageType.SHOW_PROGRESS_DIALOG) {
            showProgressDialog(event.message);
        } else if(event.messageType == MessageEvent.MessageType.DISMISS_POPUP_WINDOW) {
            if(mPopupWindow != null && mPopupWindow.isShowing()) {
                mPopupWindow.dismiss();
            }
        } else if(event.messageType == MessageEvent.MessageType.REFRESH_USER_INFO) {
            int type = Integer.parseInt(event.message);
            switch (type) {
                case InfoChoosePopupWindow.CHOOSE_GRADE:
                    mTv_grade.setText(YiKaoApplication.getGradeName());
                    break;
                case InfoChoosePopupWindow.CHOOSE_MAJOR:
                    mTv_major.setText(YiKaoApplication.getMajorName());
                    break;
                case InfoChoosePopupWindow.CHOOSE_PROVINCE:
                    mTv_province.setText(YiKaoApplication.getProvinceName());
                    break;
            }
        }
    }
}
